import React, { useRef, Ref, useEffect } from 'react';
import { OneModal } from '../one-ui/OneModal';
import { IOneModalRef } from '@/pages/type';
import { ISelectPostUser } from './type';
import pageStyles from '@/common/pageLayout.less';
import { Col, Form, message, Row, Select, Spin, TreeSelect } from 'antd';
import { getDeptPosTreeIcon, getPosIDs, getUserID, loopArray } from '@/utils';
import MyIcon from '../MyIcon';
import {
  getFlowOrgTreeByOrgIDService,
  getUserDataList,
} from '@/services/BaseLayout';

/**
 * @description: 选择岗位和人的弹窗公共组件
 * @param {string} title 标题   注意：在title前自动加上了选择  请先看一下组件title的值
 * @param {function} onClose 关闭方法
 * @param {boolean} isSelectSelf 是否可以选择到自己 true是可以 false是不可以
 * @param {function} returnSelectInfo 返回处理好的数据
 * */
const Index: React.FC<ISelectPostUser> = ({
  title = '使用人',
  onClose,
  isSelectSelf,
  returnSelectInfo,
}) => {
  /**获取组织机构树 接口 */
  const {
    getFlowOrgTreeRun,
    getFlowOrgTreeLoading,
    getFlowOrgList,
  } = getFlowOrgTreeByOrgIDService();

  const { getUserRun, getUserLoading, getUserList } = getUserDataList(
    (res: any) => {
      if (!(res && res?.msgFlag)) {
        message.error(res?.msg);
      }
    },
  );

  /**
   * 初始化获取组织机构树
   */
  useEffect(() => {
    let payload = {
      params: '0',
      flowType: '0',
      orgID: getPosIDs(),
    };
    getFlowOrgTreeRun(payload);
  }, []);

  /**
   * 表单 form
   * */
  const [sharingForm] = Form.useForm();

  /**
   * 转移客户
   */
  const sharingModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (sharingModalRef) {
      if (sharingModalRef.current) {
        if (sharingModalRef.current.onModalCancel) {
          sharingModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 确定按钮事件
   * */
  const onConfirm = () => {
    sharingForm?.validateFields()?.then((values: Record<string, any>) => {
      let treeListPos: Record<string, any>[] = loopArray(getFlowOrgList);
      let checkUsrObj = treeListPos?.filter((item: Record<string, any>) => {
        return item?.id == values?.ownPositionID;
      });
      let useObj: Record<string, any> = checkUsrObj?.[0]?.attributes;
      let params: Record<string, any> = {
        SelecterID: values?.ownerID,
        SelectPositionID: values?.ownPositionID,
        SelectPositionName: checkUsrObj?.[0]?.text,
        SelectDepartmentID: useObj?.departmentID,
        SelectDepartmentName: checkUsrObj?.[0]?.pText,
        SelectCompanyID: useObj?.companyID,
      };

      // 从该岗位下的user信息中  找到选中的一项  取出姓名
      getUserList?.forEach((item: Record<string, any>) => {
        if (item?.id === params?.SelecterID) {
          params.SelectUserName = item?.realName;
        }
      });

      // 获取公司name
      getFlowOrgList?.forEach((item: Record<string, any>) => {
        if (item?.textType == '0' && item?.id == params?.SelectCompanyID) {
          params.SelectCompanyName = item?.text;
        }
      });
      // 将处理好的数据抛出
      returnSelectInfo(params);
      onCloseModal();
    });
  };

  /**
   * 处理树数据
   * */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: (
          <div>
            {getDeptPosTreeIcon(String(item?.textType))}
            {item?.text}
          </div>
        ),
        searchtitle: item?.text,
        key: item?.id,
        value: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: item?.textType == '2' ? false : true,
      };
    });
  };

  /**处理树选中后获取用户的参数
   * @param list 传入的选中树id
   * @returns
   */
  const handleGetId = (list: any[]) => {
    let paramsIDS: any = []; //参数保存
    let checkRow = list[0]; //点击选中的节点

    // 递归树
    let loop = (treeData: any[]) => {
      treeData?.forEach((item: any) => {
        if (item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
        if (checkRow?.textType == item?.textType) {
          paramsIDS?.push(item?.id);
        }
      });
    };
    loop(list);

    let idsString = paramsIDS?.join('|');
    if (checkRow?.textType == 0) {
      return { userCompanyID: idsString };
    } else if (checkRow?.textType == 1) {
      return { userDepartmentID: idsString };
    } else if (checkRow?.textType == 2) {
      return { userPositionID: idsString };
    }
  };

  /**
   * 点击左侧树结构
   * */
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    sharingForm?.setFieldsValue({ ownerID: null });
    let userListPayload = handleGetId([selectedNodes]);
    getUserRun(userListPayload);
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={sharingModalRef}
        title={'选择' + title}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        onOk={onConfirm}
        confirmLoading={getFlowOrgTreeLoading || getUserLoading} //确定按钮loading
      >
        <Spin spinning={getFlowOrgTreeLoading || getUserLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={sharingForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label={`${title}岗位`}
                    name="ownPositionID"
                    rules={[
                      {
                        required: true,
                        message: `${title}岗位`,
                      },
                    ]}
                  >
                    <TreeSelect
                      placeholder={`请选择${title}岗位`}
                      showSearch
                      allowClear
                      treeNodeFilterProp={'searchtitle'}
                      treeData={orgTreeData(getFlowOrgList)}
                      onSelect={onTreeSelect}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label={title}
                    name="ownerID"
                    rules={[
                      {
                        required: true,
                        message: `请选择${title}`,
                      },
                    ]}
                  >
                    <Select
                      placeholder={`请选择${title}`}
                      loading={getUserLoading}
                      allowClear
                      showSearch
                      optionFilterProp={'searchtitle'}
                    >
                      {getUserList && getUserList?.length > 0 ? (
                        <>
                          {getUserList?.map((item: any) => {
                            return (
                              <Select.Option
                                // 注：限制是否能选择自己
                                disabled={
                                  isSelectSelf
                                    ? false
                                    : item?.id == getUserID()
                                    ? true
                                    : false
                                }
                                value={item?.id}
                                key={item?.id}
                                searchtitle={item?.realName}
                              >
                                <MyIcon
                                  style={{ marginRight: 5 }}
                                  type="icon-lianxiren"
                                />
                                {item?.realName}
                              </Select.Option>
                            );
                          })}
                        </>
                      ) : (
                        <></>
                      )}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};

export default Index;
